﻿using Dapper;
using HR.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Data.SqlClient;

namespace HR.Filters
{
    public class RoleFilterAttribute : Attribute,IActionFilter
    {
        //private readonly HRDBContext db;
        private readonly IConfiguration icon;
        private readonly string? strcon;
        public RoleFilterAttribute(IConfiguration icon)
        {
            this.icon = icon;
            this.strcon = icon["ConnectionStrings"];
        }

        //非异步，行为后
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
        //非异步，行为前
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //1.拿到控制器和接口
            var con = context.HttpContext.GetRouteValue("controller");
            var act = context.HttpContext.GetRouteValue("action");
            //2.拼接成数据库中路径
            var url = $"/{con}/{act}";
            int? rid = context.HttpContext.Session.GetInt32("rid");
            //3.根据角色ID查询到其下的所有可访问权限路径集合,然后遍历匹配是否存在这个路径,这里两表联查[权限中间表和权限表]用Dapper
            using(SqlConnection sqlc = new SqlConnection(strcon))
            {
                string sql = @$"select murl from [dbo].[Menu] m inner join [dbo].[RoleMenuMid] rm on m.mid=rm.Mid where rm.Rid='{rid}'";
                List<string> list = sqlc.Query<string>(sql).ToList();
                bool ck = list.Exists(ls => ls == url);
                if (!ck)
                {
                    context.Result = new ViewResult()
                    {
                        ViewName= "NotMenu"
                    };
                }
            }
        }
    }
}
